package org.jflame.commons.excel.handler;

import org.jflame.commons.excel.ExcelAccessException;
import org.jflame.commons.excel.ExcelColumnProperty;
import org.jflame.commons.excel.ExcelConvertUtils;
import org.jflame.commons.util.CollectionHelper;

import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;

public class ArrayRowWriter implements IExcelRowWriter<Object[]> {

    private Cell currentCell;
    private Object currentValue;
    // private Map<Integer,ObjectToStringConverter> columnConvertMap = new ConcurrentHashMap<>();
    private final List<ExcelColumnProperty> columnProperties;

    public ArrayRowWriter(List<ExcelColumnProperty> columnProperties) {
        if (CollectionHelper.isEmpty(columnProperties)) {
            throw new ExcelAccessException("columnPropertys must not be empty");
        }
        this.columnProperties = columnProperties;
    }

    @Override
    public void fillRow(Object[] rowData, Row excelSheetRow, int startColIndex, CellStyle defaultCellStyle) {
        if (ArrayUtils.isEmpty(rowData)) {
            return;
        }

        ExcelColumnProperty currentProperty;
        for (int cellIndex = 0; cellIndex < rowData.length; cellIndex++) {
            currentCell = excelSheetRow.createCell(startColIndex + cellIndex);
            currentValue = rowData[cellIndex];
            if (currentValue == null || StringUtils.EMPTY.equals(currentValue)) {
                currentCell.setBlank();
                continue;
            }
            currentProperty = columnProperties.get(cellIndex);

            currentCell.setCellStyle(
                    currentProperty.getColumnStyle() != null ? currentProperty.getColumnStyle() : defaultCellStyle);

            if (setCellRawValue(currentCell, currentValue, currentProperty)) {
                continue;
            }

            currentCell.setCellValue(ExcelConvertUtils.convertToCellValue(currentProperty, currentValue));

        }
    }

}
